package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDTO;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDetailDTO;
import com.hunttown.mes.rpc.domain.query.TransportTableChineseEnglishDetailDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.rpc.api.TransportSmsSendLogRpcService;
import com.hunttown.mes.rpc.domain.TransportSmsSendLogDTO;
import com.hunttown.mes.rpc.domain.query.TransportSmsSendLogDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * created by wangjunfu on 2019-05-19 01:51:48
 */
@Service
public class TransportSmsSendLogManageService {

    private final static Logger logger = LoggerFactory.getLogger(TransportSmsSendLogManageService.class);

    private final TransportSmsSendLogRpcService rpcService;
    private final TransportTableChineseEnglishManageService englishService;
    private final TransportTableChineseEnglishDetailManageService englishDetailService;
    private final AnalysisManageManageService manageService;

    @Autowired
    public TransportSmsSendLogManageService(TransportSmsSendLogRpcService rpcService, TransportTableChineseEnglishManageService englishService, TransportTableChineseEnglishDetailManageService englishDetailService, AnalysisManageManageService manageService) {
        this.rpcService = rpcService;
        this.englishService = englishService;
        this.englishDetailService = englishDetailService;
        this.manageService = manageService;
    }

    // 新增
    public TransportSmsSendLogDTO insert(TransportSmsSendLogDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(TransportSmsSendLogDTO objDTO) {
        return rpcService.updateInfoById(objDTO);
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(TransportSmsSendLogDTOQuery objDTOQuery) {
        return rpcService.updateInfoByQuery(objDTOQuery);
    }

    // 通过ID获取
    public TransportSmsSendLogDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public TransportSmsSendLogDTO getByQuery(TransportSmsSendLogDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<TransportSmsSendLogDTO> getForPage(TransportSmsSendLogDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    /**
     * 判断验证码是否正确
     *
     * @param mobile 手机号
     * @param code   验证码
     * @param entId  企业ID
     * @return TF
     */
    public Boolean judgeVerifyCode(String mobile, String code, Integer entId) {
        boolean isNext = true;

        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code)) {
            System.out.println("登录：手机号或验证码为空");
            return false;
        }

        // 通过手机号获取新的一条数据
        TransportSmsSendLogDTOQuery query = new TransportSmsSendLogDTOQuery();
        if (entId != null && entId > 0) {
            query.setEntId(entId);
        }
        query.setMobile(mobile);
        query.setOrderBy("order by id desc");
        TransportSmsSendLogDTO dto = rpcService.selectObjByQuery(query);
        if (dto == null) {
            System.out.println("登录：未获取到验证码");
            return false;
        }

        // 判断验证码是否已使用
        if (dto.getStatus() == -10) {
            System.out.println("登录：验证码已使用");
            return false;
        }

        // 判断验证码是否在有效期内
        Long currentTime = new Date().getTime();
        Long sendTime = dto.getSendTime().getTime();
        if ((currentTime - sendTime) > (dto.getEffectMinute() * 60 * 1000)) {
            return false;
        }

        // 验证码是否正确
        if (!dto.getCode().equals(code)) {
            //如果验证码不匹配，也要将其设为已使用。
            System.out.println("登录：验证码不正确");
            isNext = false;
        }

        // 更新验证码使用状态
        TransportSmsSendLogDTO update = new TransportSmsSendLogDTO();
        update.setId(dto.getId());
        if (entId != null && entId > 0) {
            update.setEntId(entId);
        }
        update.setStatus(-10);
        rpcService.updateInfoById(update);

        return isNext;
    }

    //region 数据查看

    /**
     * 组装实体信息为前台可展示的格式
     * 可做定制化的配置
     * 存放位置：各业务的Service中
     *
     * @param model     Sevelet Model
     * @param tableName 数据库表名
     * @param obj       对象
     * @return json
     */
    public Model assembleObjInfo(Model model, String tableName, TransportSmsSendLogDTO obj) {

        // 结果集返回一个map
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

        // 显示标题
        String showTitle = obj == null ? "详情" : obj.getMobile();

        // 获取数据库中英文对照表主表信息
        TransportTableChineseEnglishDTO englishDTO = englishService.getByTableName(tableName);

        if (obj == null || englishDTO == null) {
            map.put("没有查询到数据！", "");
        } else {
            Map<String, Object> origin_map = GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(obj), TransportSmsSendLogDTO.class);

            if (origin_map != null) {
                // 根据表ID（tableId）获取表字段信息
                TransportTableChineseEnglishDetailDTOQuery query = new TransportTableChineseEnglishDetailDTOQuery();
                query.setTableId(englishDTO.getId());
                query.setDeleteFlag(0);
                query.setPageSize(1000);
                Page<TransportTableChineseEnglishDetailDTO> detailPage = englishDetailService.getForPage(query);

                if (detailPage != null && detailPage.getItems().size() > 0) {
                    Object value;
                    String newfield;
                    for (TransportTableChineseEnglishDetailDTO item : detailPage.getItems()) {
                        if (item.getFrontShow() == 1) {
                            newfield = GeneralUtils.standardFields(item.getFieldName());
                            value = origin_map.get(newfield);
                            if (item.getFieldType().toUpperCase().equals("TIMESTAMP")) {
                                map.put(item.getFieldNameCn(), DateConvertUtils.cstToShortStrDate(value.toString()));
                            } else {

                                if (value == null || StringUtils.isBlank(value.toString())) {
                                    map.put(item.getFieldNameCn(), "--");
                                    continue;
                                }

                                //region 开始个性化设置
                                if (newfield.equals("adminId")) { //创建人
                                    value = manageService.getNickNameFromCache(Integer.valueOf(value.toString()));
                                }
                                if (newfield.equals("stopFlag")) { //启停用状态
                                    value = value.equals(0) ? "启用" : "停用";
                                }
                                //endregion

                                map.put(item.getFieldNameCn(), value.toString());
                            }
                        }
                    }
                }
            }
        }

        model.addAttribute("showTitle", showTitle);
        model.addAttribute("showResult", map);

        return model;
    }

    //endregion
}